import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import PageDto from './dto/page.dto';
import { WaterBills } from '@app/db/entity/WaterBills';
import { User } from '@app/db/entity/User';
import { FindOptionsWhere, In } from 'typeorm';

@Injectable()
export class WaterBillsService {
    constructor(
        private readonly db:DbService,
    ){}


    async page(dto:PageDto) {
        let result:PaginationResult<WaterBills & {user? : User,}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<WaterBills> = {

        }

        if(dto.deviceId && dto.deviceId > 0) {
            where.deviceId = dto.deviceId
        }



        


        result.total = await this.db.waterBills.count(where)

        if(result.total > 0) {

            result.rows = await this.db.waterBills.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})

            if(result.rows.length > 0) {

                const userIds:number[] = []

                result.rows.forEach(row => {
                    if(row.userId > 0 && !userIds.includes(row.userId)) {
                        userIds.push(row.userId)
                    }
                })

                if(userIds.length > 0) {
                    const users = await this.db.user.find({id : In(userIds)}, {id : true, nickname : true, avatar : true})
                    

                    if(users.length > 0) {
                        result.rows.forEach(row => {
                            if(row.userId > 0) {
                                const user = users.find(item => item.id == row.userId)
                                if(user) {
                                    row.user = user
                                }
                            }
                        })
                    }
                }
            }
        }

        return result
    }
}
